<template>
  <div>
    <vCommonPage :title="qrcodeType==='ali'?'请使用支付宝扫码支付':'请使用微信扫码支付'">
      <div slot="customContent">
        <!-- start:自定义页面内容 -->
        <div class="page-wrap">
          <div class="item-wrap">
            <div class="phone-bg" :style="{backgroundImage: 'url('+ phoneBgUrl +')'}">
              <canvas id="qrcode" class="qrcode"></canvas>
              <div class="pay-info">
               <span style="font-size:18px">姓名：{{this.$store.state.user.userinfo.name}}</span>
               <br>
              <span style="font-size:26px;color:red;">支付金额：{{this.amount}}元</span>
                <br>
              </div>
            </div>
            <el-button @click="cancelPay" class="cancel-btn" type="danger">取消支付</el-button>
          </div>  
        </div>
        <!-- end:自定义页面内容 -->
      </div>
    </vCommonPage>
  </div>
</template>
<script>
// 图像
import phoneBgUrl from '@images/payments/phone-bg.jpg'
import QRCode from 'qrcode'
import { commonPost } from '@api/data'
import { route, appointent, recipel,inptRechargeReq ,countDown} from "@js/mixins"
import {MedInsRegistTrade}from "@js/MIRegist"
import {MedInsBillConformTrade}from "@js/MIBillConform"
export default {
  mixins: [route, appointent, recipel, inptRechargeReq, countDown,MedInsRegistTrade,MedInsBillConformTrade],
  data() {
    return {
      timer: null,
      status: '',
      phoneBgUrl: phoneBgUrl,  // 手机背景图
      qrcodeType: this.$route.query.from, // 支付宝还是微信的二维码
      amount:"",//支付金额
      outTradeNo: "",
      traceNo: "",
      iscanceled:false,
        payinfo:{
        status: "",
        amount:"",
        outPayTradno:"",
        rcptNo:"",
        transNo:"",
        payWay:""
      }
    };
  },
  methods: {
    nextStep() {
     const preStageName = this.$store.state.route.preStageEnd;
       var isYbPay=this.$store.state.user.isYbPay
       let orginfo = this.$store.state.terminfo.orginfo;
      switch (preStageName) {
          case "mzgh":
            if(isYbPay&&orginfo.cmiid!='104'){//不是延吉医保挂号
              this.CMIBillConfirm();
            }
            else{
              this.sendRegConfirm();
            }
          break;
        case "mzyy":
            if(isYbPay&&orginfo.cmiid!='104'){//不是延吉医保预约取号
              this.CMIBillConfirm();
            }
            else{
              this.sendAppointent();
            }
          break;
        case "mzjs":
            if(isYbPay){
              this.CMIBillConfirm();
            }
            else{
               this.sendRecipel();
            }
          break;
           case "zycz":
          this.sendInptRechargeReq();
          break;
      }
    },
     load() {
       this.amount=this.$store.state.user.userpay
       const preStageName = this.$store.state.route.preStageEnd;
       if(preStageName==='zycz'){
          this.accountType=2;//住院账户类型2
       }
       else{
          this.accountType=1;//门诊账户类型1
       }
      },
    createQrcode(url){
      const canvas = document.getElementById('qrcode')
      QRCode.toCanvas(canvas, url, function (error) {
        if (error){
          this.$alert('请稍后重新支付', '系统异常');
        }
      })
    },
    cancelPay(){
      let data = {}
      data.url = "/api/getOrderClose"
      data.payload = {
        orderId: this.outTradeNo,
         appOrderId: this.traceNo,
         payChannel:this.qrcodeType,
         terminalId:this.$store.state.terminfo.terminfo.termId,
      }
      commonPost(data).then(() => {
        this.iscanceled=true;
        // this.$router.push({ name: "home"});
        this.$router.push({ name: "payments", query: { from: this.$store.state.route.preStageEnd } });
        this.$notify({
          title: '订单取消成功',
          message: '订单已取消，请勿继续支付',
          customClass: "custom-notify"
        });
        // this.$alert('订单已取消，请勿继续支付', '订单取消成功', {
        //   confirmButtonText: '确定'
        // });
      })
    },
  async  query(){
      let data = {}
      data.url = "/api/getPayUrl"
      data.payload = {
        terminalId:this.$store.state.terminfo.terminfo.termId,
        totalAmount:this.amount,
        payChannel:this.qrcodeType,
        patientId: this.$store.state.user.userinfo.patientId,
        accountType:this.accountType,
        CardNo: "",
        CardType: ""
      }
      commonPost(data).then(res => {
        let url = res.data.qrCode
        this.outTradeNo = res.data.orderId
        this.traceNo = res.data.appOrderId;
        this.createQrcode(url);
        this.timerhandle = setTimeout(() =>  this.dealStatus(), 5000);
      }).catch(e=>{
       this.$alert("下单失败，请重试");
      });
    },
    dealStatus() {
      const data = {}
      data.url = "/api/getPayOrderStatus"
      data.payload = {
         orderId: this.outTradeNo,
         appOrderId: this.traceNo,
         payChannel:this.qrcodeType,
         terminalId:this.$store.state.terminfo.terminfo.termId,
      }
      commonPost(data).then(res => {
        this.status=res.data.payStatus;
        if (res.data.payStatus== "success"){
          this.iscanceled=true;//防止组件销毁时取消
          this.payinfo.outPayTradno = this.outTradeNo;
          this.payinfo.transNo =  this.traceNo;
         this.payinfo.rcptNo= res.data.orderId;
          this.payinfo.status= res.data.payStatus;
          this.payinfo.payWay=this.qrcodeType;
          this.payinfo.barCode="";
         
        }
      })
    } 
  },
  computed: {
    // 计算属性
    statusData() { return this.status }
  },
  watch: {
    statusData: function (status) {
      // 当返回的新值为创建中的时候,保持3秒轮询
      if (status == 'pending') {
        this.timer = setInterval(() => {
          setTimeout(this.dealStatus, 0)
        }, 3000)
      }
      // 当返回的新值为成功的时候,关闭定时器,结束轮询
     else if (status == 'success') {
        this.$message({
          message: '支付成功！',
          type: 'success'
        });
        clearInterval(this.timer)
         this.$store.dispatch("payrecord/updatepayinfo", this.payinfo);
         this.nextStep();
      }
    }
  },
  components: {
  },
  mounted(){
      this.load();
      this.query();
  
  },
  beforeDestroy: function () {
    if(!this.iscanceled){
      this.cancelPay();
    }
    clearInterval(this.timer)
  },
};
</script>
<style scoped>
  .page-wrap {
    position: absolute;
    top: 0;
    bottom: 0;
    display: flex;
    justify-content: center;
    align-items: center;
  }
  .item-wrap{
    position: absolute;
    text-align: center;
  }
  .phone-bg{
    width: 500px;
    padding: 0 150px;
    box-sizing: border-box;
    height: 500px;
    border-radius: 250px;
    background-size: cover;
    background-repeat: no-repeat;
    display: flex;
    justify-content: center;
    flex-wrap: wrap;
  }
  .pay-info{
    position: absolute;
    box-sizing: border-box;
    top: 250px;
    width: 200px;
    padding: 0 20px;
    line-height: 24px;
    font-size: 16px;
    color: #666;
    text-align: left;
  }
  .qrcode{
    position: relative;
    top: 100px;
  }
  .cancel-btn{
    margin: 30px 0 0 0;
    font-size: 18px;
    padding: 20px 30px;
  }
</style>
<style>
  .custom-notify{
    right: 0;
    top: 910px !important;
  }
</style>